using System;
using System.Reflection;

namespace FrameworkX.ObjectSpace.Util
{
	/// <summary>
	/// A helper class for soem common functions used internally.
	/// </summary>
	internal class CommonHelper
	{


        public static T GetAttribute<T>(PropertyInfo obj)
        {
            object attr = GetAttribute(obj, typeof(T)) ;
            if (obj != null)
            {
                return (T) attr;
            }
            else
            {
                return default(T);
            }
        }

		/// <summary>
		/// Gets an attribute if the property implements the attribute.
		/// </summary>
		/// <param name="obj">The property to inspect</param>
		/// <param name="attributeType">Type of attribute to look for</param>
		/// <returns>Searched attribute</returns>
		public static object GetAttribute (PropertyInfo obj, Type attributeType )
		{
			object[] attributes = null;
			PropertyInfo pinfo = (PropertyInfo)obj;
			attributes = pinfo.GetCustomAttributes (attributeType, false);

			if (attributes.Length>0)
			{
				return (Attribute) attributes[0];
			}
			else
			{
				return null;
			}
		}

        public static T GetAttribute<T>(Type obj)
        {
            object attr = GetAttribute(obj, typeof(T));
            if (obj != null)
            {
                return (T)attr;
            }
            else
            {
                return default(T);
            }
        }

		/// <summary>
		/// Gets an attribute if the type implements the attribute.
		/// </summary>
		/// <param name="prop">The property to inspect</param>
		/// <param name="attributeType">Type of attribute to look for</param>
		/// <returns>Searched attribute</returns>
        public static object GetAttribute(Type obj, Type attributeType)
		{
			object[] attributes = null;
			Type typeInfo = (Type)obj;
			attributes = typeInfo.GetCustomAttributes (attributeType, false);

			if (attributes.Length>0)
			{
				return (Attribute) attributes[0];
			}
			else
			{
				return null;
			}
		}



	}
}
